﻿//解析Url传参数
function getUrlParam(name) {
    var reg = new RegExp("(^/?|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return null;
}

//加载表单
function loadFrom(mainForm, data) {
    if (mainForm)
        mainForm = $("form:first");
    //GetDate(data);
    if (typeof data == "string")
        data = eval("(" + data + ")");
    for (var p in data) {
        p = p.replace("$", "");
        var ele = $("[name='" + p + "']", mainForm);
        if (ele) {
            if (ele.is(":checkbox,:radio")) {
                //$(ele[0]).attr("checked", data[p] ? true : false);
                ele[0].checked = data[p] ? true : false;
            }
            else {
                ele.val(data[p]);
            }
        }
    }
    var managers = $.ligerui.find($.ligerui.controls.Input);
    for (var i = 0; i < managers.length; i++) {
        //改变了表单的值，需要调用这个方法来更新ligerui样式
        var o = managers[i];
        o.updateStyle();
        if (managers[i] instanceof $.ligerui.controls.TextBox)
            o.checkValue();
    }

}

//解析时间格式
function changeDateFormat(cellval) {
    var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    return date.getFullYear() + "-" + month + "-" + currentDate;
}

//form是jquery对象
function validateForm(form) {
    form.validate({
        //调试状态，不会提交数据的
        debug: true,
        errorPlacement: function (lable, element) {
            if (element.hasClass("l-textarea")) {
                //element.addClass("l-textarea-invalid");
                element.ligerTip({ content: lable.html(), target: element[0] });
            }
            else if (element.hasClass("l-text-field")) {
                //element.parent().addClass("l-text-invalid");
                element.parent().ligerTip({ content: lable.html(), target: element[0] });
            }
            else if (element.hasClass("l-text-combobox")) {
                element.parent().addClass("l-text-invalid");
                element.parent().ligerTip({ content: lable.html(), target: element[0] });
            }
            else if (element.hasClass("error")) {
                element.parent().addClass("l-text-invalid");
                element.parent().ligerTip({ content: lable.html(), target: element[0] });
            }
        },
        success: function (lable) {
            lable.ligerHideTip();
            lable.remove();
        },
        submitHandler: function () {
            $("form .l-text,.l-textarea").ligerHideTip();
            alert("Submitted!");
        }
    });
    return form.valid();
}
//带验证、带loading的提交
function submitForm(mainform, success, error, targetUrl, data) {

    if (!mainform)
        mainform = $("form:first");
    if (validateForm(mainform)) {
        mainform.ajaxSubmit({
            dataType: 'html',
            url: targetUrl || mainform.attr("action"),
            success: success,
            async: false,
            data: data,
            beforeSubmit: function (formData, jqForm) {
                //针对复选框和单选框 处理
                $(":checkbox,:radio", jqForm).each(function () {
                    if (!existInFormData(formData, this.name)) {
                        formData.push({ name: this.name, type: this.type, value: this.checked });
                    }
                });
                for (var i = 0, l = formData.length; i < l; i++) {
                    var o = formData[i];
                    if (o.type == "checkbox" || o.type == "radio") {
                        o.value = $("[name=" + o.name + "]", jqForm)[0].checked ? "true" : "false";
                    }
                }
            },
            error: error
        });
    }
}


function existInFormData(formData, name) {
    for (var i = 0, l = formData.length; i < l; i++) {
        var o = formData[i];
        if (o.name == name) return true;
    }
    return false;
}

//对话框和显示加载2014.03.20
//显示对话框
function showMessage(msg, btns, funcOk, funcCancel, funcClose, objJson, parentPage) {
    //    if (window.top.location.href != location.href) {
    //        window.top.showAlert(msg, btns, funcOk, funcCancel, funcClose, objJson, parentPage);
    //    } else {
    if (!btns) btns = "ok";
    switch (btns.toLowerCase()) {
        case "okcancel":
            jQuery.messager.confirm("", msg, function (r) {
                if (r) {
                    if (funcOk) {
                        if (jQuery.isFunction(funcOk)) {
                            funcOk(objJson);
                        } else {
                            eval(funcOk + "(objJson);")
                        };
                    }
                } else {
                    if (funcCancel) {
                        if (jQuery.isFunction(funcCancel)) {
                            funcCancel(objJson);
                        } else {
                            eval(funcCancel + "(objJson);")
                        }
                    }
                }
                if (parentPage) parentPage.reload();
                //if (funcReload && jQuery.isFunction(funcReload)) funcReload();
            });
            break;
        case "none":
            var win = jQuery.messager.progress({
                title: "",
                interval: 100,
                msg: msg
            });
            setTimeout(function () {
                jQuery.messager.progress("close");
                if (funcClose) {
                    if (jQuery.isFunction(funcClose)) {
                        funcClose(objJson)
                    } else {
                        eval(funcClose + "(objJson);")
                    }
                }
                if (parentPage) parentPage.reload();
            }, 1000)
            break;
        default:
            jQuery.ligerDialog.alert("", msg, "info", funcOk);
            break;
    }
    //    }
}


function showLoading(message) {
    message = message || "正在加载中...";
    $('body').append("<div class='jloading'><img src=\"../../Scripts/LigerUI/images/loading.gif\" alt=\"加载中...\" />" + message + "</div>");
    $.ligerui.win.mask();
};

function hideLoading(message) {
    $('body > div.jloading').remove();
    $.ligerui.win.unmask({ id: new Date().getTime() });
}

//重载ligerGrid样式
$.ligerDefaults.Grid.editors['chk'] = $.ligerDefaults.Grid.editors['checkbox'] = {
    create: function (container, editParm) {
        var input = $("<input type='checkbox' />");
        container.append(input);
        input.ligerCheckBox();
        return input;
    },
    getValue: function (input, editParm) {
        return input[0].checked ? 1 : 0;
    },
    setValue: function (input, value, editParm) {
        input.val(value ? true : false);
        input.attr("checked", value ? true : false);
        liger.get(input).updateStyle();
    },
    resize: function (input, width, height, editParm) {
        input.liger('option', 'width', width);
        input.liger('option', 'height', height);
    },
    destroy: function (input, editParm) {
        input.liger('destroy');
    }
};


/*
表格 扩展
*/

$.extend($.ligerui.controls.Grid.prototype, {
    //_initBuildHeader: function () {
    //    var g = this, p = this.options;
    //    if (p.title) {
    //        $(".l-panel-header-text", g.header).html(p.title);
    //        if (p.headerImg)
    //            g.header.append("<img src='" + p.headerImg + "' />").addClass("l-panel-header-hasicon");
    //    }
    //    else {
    //        g.header.hide();
    //    }
    //    if (p.toolbar) {
    //        if ($.fn.ligerToolBar)
    //            g.toolbarManager = g.topbar.ligerToolBar(p.toolbar);
    //    }
    //    else {
    //        g.topbar.remove();
    //    }
    //},
    //addEditRow: function (rowdata) {
    //    var g = this;
    //    rowdata = g.add(rowdata);
    //    return g.beginEdit(rowdata);
    //},
    getEditingRow: function () {
        var g = this;
        for (var i = 0, l = g.rows.length; i < l; i++) {
            if (g.rows[i]._editing)
                return g.rows[i];
        }
        return null;
    },
    getUnChangedRow: function () {
        var g = this;
        for (var i = 0, l = g.rows.length; i < l; i++) {
            if (g.rows[i].__status.toLowerCase() == "add")
                return g.rows[i];
        }
        return null;

    }, getEditingRows: function () {
        var g = this;
        var editingRow = new Array();
        for (var i = 0, l = g.rows.length; i < l; i++) {
            if (g.rows[i]._editing)
                editingRow.push(g.rows[i]);
        }
        return editingRow;
    }

    //,
    //getChangedRows: function () {
    //    var g = this, changedRows = [];
    //    pushRows(g.getDeleted(), 'delete');
    //    pushRows(g.getUpdated(), 'update');
    //    pushRows(g.getAdded(), 'add');
    //    return changedRows;

    //    function pushRows(rows, status) {
    //        if (!rows || !rows instanceof Array) return;
    //        for (var i = 0, l = rows.length; i < l; i++) {
    //            changedRows.push($.extend({}, rows[i], { __status: status }));
    //        }
    //    }

    //}
});

//搜索框 收缩/展开
$(".searchTitle .toggleBtn").live('click', function () {
    if ($(this).hasClass("toggleBtn-down")) $(this).removeClass("togglebtn-down");
    else $(this).addClass("togglebtn-down");
    var searchbox = $(this).parent().nextAll("div.searchbox:first");
    searchbox.slideToggle('fast');
});

//扩展Date格式化输出
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month 
        "d+": this.getDate(), //day 
        "h+": this.getHours(), //hour 
        "m+": this.getMinutes(), //minute 
        "s+": this.getSeconds(), //second 
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
        "S": this.getMilliseconds() //millisecond 
    }

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}

//得到当前日期
function getNowDate(date) {
    if (date instanceof Date) {
        var now = "";
        now = date.getFullYear() + "-"; //读英文就行了
        now += (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1)) + "-";
        now += (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
        now += (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
        now += date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        return now;
    }
}

(function ($) {
    var _addItem = $.ligerui.controls.ToolBar.prototype.addItem;
    $.extend($.ligerui.controls.ToolBar.prototype, {
        addItem: function (item) {
            var g = this, p = this.options;
            if (item.form && item.id) {
                var ditem = $('<div class="l-toolbar-item"></div>');
                g.toolBar.append(ditem);
                ditem.append($('#' + item.id));
                return;
            }
            _addItem.apply(g, arguments);
        }
    });
}(jQuery));

//去重扩展
function uniqueArray(arr, fn) {
    if (!(arr instanceof Array)) {
        return arr;
    }
    var len = arr.length,
       result = arr.slice(0),
       i, datum;

    if ('function' != typeof fn) {
        fn = function (item1, item2) {
            return item1 === item2;
        };
    }

    // 从后往前双重循环比较
    // 如果两个元素相同，删除后一个
    while (--len > 0) {
        datum = result[len];
        i = len;
        while (i--) {
            if (fn(datum, result[i])) {
                result.splice(len, 1);
                break;
            }
        }
    }

    len = arr.length = result.length;
    for (i = 0; i < len; i++) {
        arr[i] = result[i];
    }
    return arr;
}

//function setUrlPara(url, param) {
//    var r = "";
//    if (param instanceof Object) {
//        for (var item in param) {
//            var reg = new RegExp("(^/?|&)" + item + "=([^&]*)(&|$)", "i");
//            r = url.match(reg);
//            if (r != null)
//                url = url.replace(r[2], param[item]);
//            else {
//                url = url + "&" + item + "=" + param[item];
//            }
//        }
//        return url;
//    }
//}

